#ifndef OS_SYNCLOCK_H
    #define OS_SYNCLOCK_H

    #include<os/task.h>
    #include<os/spinlock.h>
    #include<os/semaphore.h>
    #include<lib/type.h>
    #include<os/schedule.h>

    typedef struct 
    {
        task_t *holder;         //lock current holder
        semaphore_t semaphore;  //semaphore
        uint8_t reapt_count;    //lock holder counts
    }synclock_t;

    #define SYNC_LOCK_INIT(lock)    \
    {  .holder=NULL\
    ,  .semaphore=SEMAPHORE_INIT((lock).semaphore,1) \
    ,  .reapt_count=0   \
    }

    #define DEFINE_SYNC_LOCK(lock)  \
        synclock_t lock=SYNC_LOCK_INIT(lock)


    static inline void SyncLockInit(synclock_t *lock)
    {
        lock->holder=(task_t*)NULL;
        lock->reapt_count=0;
        SemaphoreInit(&lock->semaphore,1);
    }

    static inline void SyncLockLock(synclock_t *lock)
    {
        //holder no is cur_task
        //can to do down semaphore
        if(lock->holder!=cur_task)
        {
            SemaphoreDown(&lock->semaphore);
            lock->holder=cur_task;
            lock->reapt_count=1;
        }
        else
        {
            //or,task holder lock , reapt_count+1
            lock->reapt_count++;
        }
    }

    static inline void SyncLockUnlock(synclock_t *lock)
    {
        //holder no is cur_task,return 
        if(lock->holder!=cur_task)
            return ;
        //wait to reapt count full free
        if(lock->reapt_count>1)
        {   
            lock->reapt_count--;
            return;
        }
        //only had one lock
        if(lock->reapt_count!=1)
            return;
        //free lock 
        lock->holder=NULL;
        lock->reapt_count=0;
        SemaphoreUp(&lock->semaphore);  //sync unlock free semaphore
    }

    


#endif